/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.service;

import com.xiaoleilu.hutool.DateUtil;
import com.xiaoleilu.hutool.StrUtil;
import com.xnck.mfpms.dao.*;
import com.xnck.mfpms.entity.*;
import com.xnck.mfpms.exception.ValidateException;
import com.xnck.mfpms.util.MD5Utils;
import com.xnck.mfpms.util.PagerUtil;
import com.xnck.mfpms.util.ValidatorUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserService{

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private ActionDao actionDao;

    @Autowired
    private RuleDao ruleDao;

    @Autowired
    private UserRuleDao userRuleDao;

    @Autowired
    private UserMenuDao userMenuDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private UserActionDao userActionDao;

    /**
     * 获得用户
     * @param userId
     * @return
     */
    public UserInfo get(String userId){
        return userDao.get(userId);
    }

    /**
     * 获得符合条件的用户总数量
     * @param userName
     * @return
     */
    public int getsCount(String userName){
        Criteria cri = Cnd.cri();
        this.getSearchCnd(cri, userName);
        return userDao.searchCount(cri);
    }

    /**
     * 分页获得符合条件的用户
     * @param userName
     * @param orderName
     * @param orderType
     * @param pageSize
     * @param beginIndex
     * @return
     */
    public List<UserInfo> gets(String userName, String orderName, String orderType,
                               int pageSize, int beginIndex){
        Criteria cri = Cnd.cri();
        this.getSearchCnd(cri, userName);
        PagerUtil.getSearchOrder(cri, UserInfo.FIELD_DISPLAYNAME, orderName, orderType);
        int currentPage = PagerUtil.getCurrentPage(beginIndex, pageSize);
        return userDao.searchByPage(cri, currentPage, pageSize);
    }

    /**
     * 获得用户
     * @param serUserId 当前操作查询的人员ID
     * @param userId 被查询的人员ID
     * @return
     */
    public UserInfo getByRule(String serUserId, String userId) throws Exception {
        List<UserInfo> users = userDao.getUsersByRule(serUserId, Cnd.where(UserInfo.FIELD_ID, "=", userId));
        if (users.size() == 0){
            throw new ValidateException("用户不存在");
        }
        return users.get(0);
    }

    /**
     * 获得符合条件的用户总数量
     * @param byUserId
     * @param userName
     * @return
     */
    public int getsCountByRule(String byUserId, String userName){
        Criteria cri = Cnd.cri();
        this.getSearchCnd(cri, userName);
        return userDao.getUsersCountByRule(byUserId, cri);
    }

    /**
     * 分页获得符合条件的用户
     * @param byUserId
     * @param userName
     * @param orderName
     * @param orderType
     * @param pageSize
     * @param beginIndex
     * @return
     */
    public List<UserInfo> getUsersByRule(String byUserId, String userName,
                                         String orderName, String orderType,
                                         int pageSize, int beginIndex){
        Criteria cri = Cnd.cri();
        this.getSearchCnd(cri, userName);
        PagerUtil.getSearchOrder(cri, UserInfo.FIELD_DISPLAYNAME, orderName, orderType);
        int currentPage = PagerUtil.getCurrentPage(beginIndex, pageSize);
        return userDao.getUsersByRule(byUserId, cri, currentPage, pageSize);
    }

    /**
     * 检查人员是否可以访问某个资源
     * @param userId 被验证的人员ID
     * @param resourceCode 资源代码
     * @return
     * @author:zhangmengliang
     * @date: 2015年11月4日
     */
    public Boolean getCanRequestResource(String userId, String resourceCode){
        List<ResourceInfo> resources = resourceDao.getsForUserRoleAction(userId,
                Cnd.where(ResourceInfo.FIELD_CODE, "=", resourceCode).and(ResourceInfo.FIELD_ENABLE, "=", true));
        if (resources != null && resources.size() > 0) {
            return true;
        }
        resources = resourceDao.getsForUserAction(userId,
                Cnd.where(ResourceInfo.FIELD_CODE, "=", resourceCode).and(ResourceInfo.FIELD_ENABLE, "=", true));
        if (resources != null && resources.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据视图名称获得某个人员有权限访问的资源
     * @param userId 人员ID
     * @param viewName 视图名称
     * @return
     * @author:zhangmengliang
     * @date: 2015年11月4日
     */
    public List<ResourceInfo> getCanRequestResourcesForView(String userId, String viewName){
        List<ResourceInfo> returnResources = new ArrayList<ResourceInfo>();
        //根据人员所属角色获得可以访问的资源
        List<ResourceInfo> resources = resourceDao.getsForUserRoleAction(userId,
                Cnd.where(ResourceInfo.FIELD_VIEWNAME, "=", viewName).and(ResourceInfo.FIELD_ENABLE, "=", true));
        returnResources.addAll(resources);
        //根据人员直接获得可以访问的资源
        resources = resourceDao.getsForUserAction(userId,
                Cnd.where(ResourceInfo.FIELD_VIEWNAME, "=", viewName).and(ResourceInfo.FIELD_ENABLE, "=", true));
        returnResources.addAll(resources);
        return returnResources;
    }

    /**
     * 创建用户
     * @param displayName
     * @param name
     * @param loginName
     * @param loginPwd
     * @param email
     * @param enable
     */
    @Transactional(rollbackFor = Exception.class)
    public void create(String creatorId, String displayName, String name, String loginName, String loginPwd,
                       String email, boolean enable) throws Exception {
        this.checkUserInsertInput(displayName, name, loginName, loginPwd, email);
        UserInfo creator = this.getCreator(creatorId);
        String userId = UUID.randomUUID().toString();
        loginPwd = MD5Utils.MD5Encode(loginPwd);
        userDao.insert(userId, creator.getCompanyid(), name, displayName, email, creatorId, enable, DateUtil.date());
        accountDao.insert(UUID.randomUUID().toString(), loginName, loginPwd, userId, DateUtil.date());
    }

    /**
     * 修改用户
     * @param userId
     * @param displayName
     * @param name
     * @param loginPwd
     * @param email
     * @param enable
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(String userId, String displayName, String name, String loginPwd,
                       String email, boolean enable) throws Exception {
        this.checkUserUpdateInput(userId, displayName, name, loginPwd, email);
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("用户不存在");
        }
        List<AccountInfo> accounts = accountDao.search(Cnd.where(AccountInfo.FIELD_USERID, "=", userId));
        if (accounts.size() == 0){
            throw new ValidateException("登录用户不存在");
        }
        user.setDisplayname(displayName);
        user.setName(name);
        user.setEmail(email);
        user.setEnable(enable);
        if(StrUtil.isNotBlank(loginPwd)){
            AccountInfo account = accounts.get(0);
            if (null != account && !"admin".equals(account.getLoginname())){
                account.setLoginpwd(loginPwd);
                accountDao.update(account);
            }
        }
        userDao.update(user);
    }

    /**
     * 删除用户信息
     * @param userIds
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletes(String userIds) throws Exception {
        if (null == userIds || userIds.length() == 0){
            return;
        }
        String[] arryUserId = userIds.split(",");
        userRoleDao.clear(Cnd.where(UserRole.FIELD_USERID, "in", arryUserId));
        userMenuDao.clear(Cnd.where(UserMenu.FIELD_USERID, "in", arryUserId));
        userRuleDao.clear(Cnd.where(UserRule.FIELD_USERID, "in", arryUserId));
        userActionDao.clear(Cnd.where(UserAction.FIELD_USERID, "in", arryUserId));
        accountDao.clear(Cnd.where(AccountInfo.FIELD_USERID, "in", arryUserId));
        userDao.clear(Cnd.where(UserInfo.FIELD_ID, "in", arryUserId));

    }

    /**
     * 已关联角色数量
     * @param roleName
     * @return
     */
    public int getJoinedRolesCount(String userId, String roleName){
        Criteria cri = Cnd.cri();
        if (StrUtil.isNotBlank(roleName)) {
            cri.where().andLike(RoleInfo.FIELD_DISPLAYNAME, roleName);
        }
        return roleDao.getRolesCountJoinUser(userId, cri);
    }

    /**
     * 未关联角色数量
     * @param userId
     * @param roleName
     * @return
     */
    public int getNoJoinRolesCount(String userId, String roleName){
        Criteria cri = Cnd.cri();
        if (StrUtil.isNotBlank(roleName)) {
            cri.where().andLike(RoleInfo.FIELD_DISPLAYNAME, roleName);
        }
        return roleDao.getRolesCountNotJoinUser(userId, cri);
    }

    /**
     * 已关联角色
     * @return
     * @throws Exception
     */
    public List<RoleInfo> getJoinedRoles(String userId, String roleName,
                                               String orderName, String orderType,
                                               int pageSize, int beginIndex) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        Criteria cri = Cnd.cri();
        if (StrUtil.isNotBlank(roleName)) {
            cri.where().andLike(RoleInfo.FIELD_DISPLAYNAME, roleName);
        }
        PagerUtil.getSearchOrder(cri, RoleInfo.FIELD_DISPLAYNAME, orderName, orderType);
        int currentPage = PagerUtil.getCurrentPage(beginIndex, pageSize);
        return roleDao.getRolesJoinUser(userId, cri, currentPage, pageSize);
    }

    /**
     * 未已关联角色
     * @return
     * @throws Exception
     */
    public List<RoleInfo> getNoJoinRoles(String userId, String roleName,
                                               String orderName, String orderType,
                                               int pageSize, int beginIndex) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        Criteria cri = Cnd.cri();
        if (StrUtil.isNotBlank(roleName)) {
            cri.where().andLike(RoleInfo.FIELD_DISPLAYNAME, roleName);
        }
        PagerUtil.getSearchOrder(cri, RoleInfo.FIELD_DISPLAYNAME, orderName, orderType);
        int currentPage = PagerUtil.getCurrentPage(beginIndex, pageSize);
        return roleDao.getRolesNotJoinUser(userId, cri, currentPage, pageSize);
    }

    /**
     * 关联人员和角色
     * @param userId 被关联人
     * @param roleIdStr 待关联角色列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void joinRoles(String userId, String roleIdStr) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        if (StrUtil.isBlank(roleIdStr)){
            throw new ValidateException("角色不存在");
        }
        String[] roleIds = roleIdStr.split(",");
        userDao.findLink(user, UserInfo.FIELD_ROLES);
        List<String> roleIdList = this.getRoleIdNotJoin(roleIds, user.getRoles());
        if (roleIdList.size() > 0){
            List<RoleInfo> roles = roleDao.search(Cnd.where(RoleInfo.FIELD_ID, "in", roleIdList.toArray(new String[roleIdList.size()])));
            if (roles.size() > 0){
                user.setRoles(roles);
                userDao.insertRelation(user, UserInfo.FIELD_ROLES);
            }
        }
    }

    /**
     * 取消关联人员和角色
     * @param userId 被关联人
     * @param roleIdStr 被关联角色列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelJoinRole(String userId, String roleIdStr) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        if (StrUtil.isBlank(roleIdStr)){
            throw new ValidateException("角色不存在");
        }
        String[] roleIds = roleIdStr.split(",");
        userDao.findLink(user, UserInfo.FIELD_ROLES);
        List<String> roleIdList = this.getRoleIdJoin(roleIds, user.getRoles());
        if (roleIdList.size() > 0){
            userRoleDao.clear(Cnd.where(UserRole.FIELD_USERID, "=", userId)
                    .and(UserRole.FIELD_ROLEID, "in", roleIdList.toArray(new String[roleIdList.size()])));
        }
    }

    /**
     * 已关联角色
     * @return
     * @throws Exception
     */
    public List<RoleInfo> getJoinedRoles(String byUserId, String userId, String roleName,
                                                 String orderName, String orderType,
                                                 int pageSize, int beginIndex) throws Exception {
        List<UserInfo> users = userDao.getUsersByRule(byUserId, Cnd.where(UserInfo.FIELD_ID, "=", userId));
        if (users.size() == 0){
            throw new ValidateException("用户不存在");
        }
        Criteria cri = Cnd.cri();
        if (StrUtil.isNotBlank(roleName)) {
            cri.where().andLike(RoleInfo.FIELD_DISPLAYNAME, roleName);
        }
        PagerUtil.getSearchOrder(cri, RoleInfo.FIELD_DISPLAYNAME, orderName, orderType);
        int currentPage = PagerUtil.getCurrentPage(beginIndex, pageSize);
        return roleDao.getRolesJoinUser(userId, cri, currentPage, pageSize);
    }

    /**
     * 未已关联角色
     * @return
     * @throws Exception
     */
    public List<RoleInfo> getNoJoinRoles(String byUserId, String userId, String roleName,
                                                 String orderName, String orderType,
                                                 int pageSize, int beginIndex) throws Exception {
        List<UserInfo> users = userDao.getUsersByRule(byUserId, Cnd.where(UserInfo.FIELD_ID, "=", userId));
        if (users.size() == 0){
            throw new ValidateException("用户不存在");
        }
        Criteria cri = Cnd.cri();
        if (StrUtil.isNotBlank(roleName)) {
            cri.where().andLike(RoleInfo.FIELD_DISPLAYNAME, roleName);
        }
        PagerUtil.getSearchOrder(cri, RoleInfo.FIELD_DISPLAYNAME, orderName, orderType);
        int currentPage = PagerUtil.getCurrentPage(beginIndex, pageSize);
        return roleDao.getRolesNotJoinUser(userId, cri, currentPage, pageSize);
    }

    /**
     * 关联人员和角色
     * @param byUserId 操作者
     * @param userId 被关联人
     * @param roleIdStr 待关联角色列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void joinRole(String byUserId, String userId, String roleIdStr) throws Exception {
        List<UserInfo> users = userDao.getUsersByRule(byUserId, Cnd.where(UserInfo.FIELD_ID, "=", userId));
        if (users.size() == 0){
            throw new ValidateException("用户不存在");
        }
        if (StrUtil.isBlank(roleIdStr)){
            throw new ValidateException("角色不存在");
        }
        String[] roleIds = roleIdStr.split(",");
        UserInfo user = users.get(0);
        userDao.findLink(user, UserInfo.FIELD_ROLES);
        List<String> roleIdList = this.getRoleIdNotJoin(roleIds, user.getRoles());
        if (roleIdList.size() > 0){
            List<RoleInfo> roles = roleDao.search(Cnd.where(RoleInfo.FIELD_ID, "in", roleIdList.toArray(new String[roleIdList.size()])));
            if (roles.size() > 0){
                user.setRoles(roles);
                userDao.insertRelation(user, UserInfo.FIELD_ROLES);
            }
        }
    }

    /**
     * 取消关联人员和角色
     * @param byUserId 操作者
     * @param userId 被关联人
     * @param roleIdStr 被关联角色列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelJoinRole(String byUserId, String userId, String roleIdStr) throws Exception {
        List<UserInfo> users = userDao.getUsersByRule(byUserId, Cnd.where(UserInfo.FIELD_ID, "=", userId));
        if (users.size() == 0){
            throw new ValidateException("用户不存在");
        }
        if (StrUtil.isBlank(roleIdStr)){
            throw new ValidateException("角色不存在");
        }
        String[] roleIds = roleIdStr.split(",");
        UserInfo user = users.get(0);
        userDao.findLink(user, UserInfo.FIELD_ROLES);
        List<String> roleIdList = this.getRoleIdJoin(roleIds, user.getRoles());
        if (roleIdList.size() > 0){
            userRoleDao.clear(Cnd.where(UserRole.FIELD_USERID, "=", userId)
                    .and(UserRole.FIELD_ROLEID, "in", roleIdList.toArray(new String[roleIdList.size()])));
        }
    }

    /**
     * 人员与菜单的关联关系
     * @param userId
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getMenuNodes(String userId) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        List<MenuInfo> menus = menuDao.search(Cnd.orderBy().asc(MenuInfo.FIELD_ORDERNO));
        userDao.findLink(user, UserInfo.FIELD_MENUS);
        List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
        for (MenuInfo menu: menus) {
            Map<String, Object> node = new HashMap<String, Object>();
            node.put("id", menu.getId());
            node.put("name", menu.getDisplayname());
            node.put("pId", menu.getParentid());
            boolean isChecked = false;
            for (MenuInfo joinMenu : user.getMenus()) {
                if (joinMenu.getId().equals(menu.getId())){
                    isChecked = true;
                }
            }
            node.put("checked", isChecked);
            nodes.add(node);
        }
        return nodes;
    }

    /**
     * 关联人员和菜单
     * @param userId 被关联人
     * @param menuIdStr 被关联菜单列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void joinMenu(String userId, String menuIdStr) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        if (StrUtil.isBlank(menuIdStr)){
            throw new ValidateException("菜单不存在");
        }
        String[] menuIds = menuIdStr.split(",");
        userDao.clearLinks(user, UserInfo.FIELD_MENUS);
        List<MenuInfo> menus = menuDao.search(Cnd.where(MenuInfo.FIELD_ID, "in", menuIds));
        if (menus.size() > 0){
            user.setMenus(menus);
            userDao.insertRelation(user, UserInfo.FIELD_MENUS);
        }
    }

    /**
     * 人员与权限的关联关系
     * @param userId
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getActionNodes(String userId) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        List<ActionInfo> actions = actionDao.search(Cnd.orderBy().asc(ActionInfo.FIELD_DISPLAYNAME));
        userDao.findLink(user, UserInfo.FIELD_ACTIONS);
        List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
        for (ActionInfo action: actions) {
            Map<String, Object> node = new HashMap<String, Object>();
            node.put("id", action.getId());
            node.put("name", action.getDisplayname());
            node.put("pId", action.getParentid());
            boolean isChecked = false;
            for (ActionInfo joinAction : user.getActions()) {
                if (joinAction.getId().equals(action.getId())){
                    isChecked = true;
                }
            }
            node.put("checked", isChecked);
            nodes.add(node);
        }
        return nodes;
    }

    /**
     * 关联人员和权限
     * @param userId 被关联人
     * @param actionIdStr 被关联权限列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void joinAction(String userId, String actionIdStr) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        if (StrUtil.isBlank(actionIdStr)){
            throw new ValidateException("权限不存在");
        }
        String[] actionIds = actionIdStr.split(",");
        userDao.clearLinks(user, UserInfo.FIELD_ACTIONS);
        List<ActionInfo> actions = actionDao.search(Cnd.where(ActionInfo.FIELD_ID, "in", actionIds));
        if (actions.size() > 0){
            user.setActions(actions);
            userDao.insertRelation(user, UserInfo.FIELD_ACTIONS);
        }
    }

    /**
     * 人员与规则的关联关系
     * @param userId
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getRuleNodes( String userId) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        List<RuleInfo> rules = ruleDao.search(Cnd.orderBy().asc(RuleInfo.FIELD_DISPLAYNAME));
        userDao.findLink(user, UserInfo.FIELD_RULES);
        List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
        for (RuleInfo rule: rules) {
            Map<String, Object> node = new HashMap<String, Object>();
            node.put("id", rule.getId());
            node.put("name", rule.getDisplayname());
            node.put("pId", rule.getParentid());
            boolean isChecked = false;
            for (RuleInfo joinRule : user.getRules()) {
                if (joinRule.getId().equals(rule.getId())){
                    isChecked = true;
                }
            }
            node.put("checked", isChecked);
            nodes.add(node);
        }
        return nodes;
    }

    /**
     * 关联人员和规则
     * @param userId 被关联人
     * @param ruleIdStr 被关联规则列表(以逗号相隔)
     */
    @Transactional(rollbackFor = Exception.class)
    public void joinRule(String userId, String ruleIdStr) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("人员不存在");
        }
        if (StrUtil.isBlank(ruleIdStr)){
            throw new ValidateException("权限不存在");
        }
        String[] ruleIds = ruleIdStr.split(",");
        userDao.clearLinks(user, UserInfo.FIELD_RULES);
        List<RuleInfo> rules = ruleDao.search(Cnd.where(RuleInfo.FIELD_ID, "in", ruleIds));
        if (rules.size() > 0){
            user.setRules(rules);
            userDao.insertRelation(user, UserInfo.FIELD_RULES);
        }
    }

    /**
     * 获得查询条件
     * @param cri
     * @param userName
     */
    private void getSearchCnd(Criteria cri, String userName){
        if (StrUtil.isNotBlank(userName)){
            cri.where().and(
                    Cnd.exps(UserInfo.FIELD_DISPLAYNAME, "like", "%" + userName + "%"));
        }
    }


    /**
     * 获得传入的ID中未关联的角色
     * @param roleIds
     * @param joinRoles
     * @return
     */
    private List<String> getRoleIdNotJoin(String[] roleIds, List<RoleInfo> joinRoles){
        List<String> roleIdList = new ArrayList<String>();
        for (String roleId : roleIds) {
            boolean isIn = false;
            for (RoleInfo role : joinRoles) {
                if (role.getId().equals(roleId)){
                    isIn = true;
                    break;
                }
            }
            if (!isIn){
                roleIdList.add(roleId);
            }
        }
        return roleIdList;
    }

    /**
     * 获得传入的ID中已关联的角色
     * @param roleIds
     * @param joinRoles
     * @return
     */
    private List<String> getRoleIdJoin(String[] roleIds, List<RoleInfo> joinRoles){
        List<String> roleIdList = new ArrayList<String>();
        for (String roleId : roleIds) {
            boolean isIn = false;
            for (RoleInfo role : joinRoles) {
                if (role.getId().equals(roleId)){
                    isIn = true;
                    break;
                }
            }
            if (isIn){
                roleIdList.add(roleId);
            }
        }
        return roleIdList;
    }

    /**
     * 获得创建者信息
     * @param userId
     * @return
     * @throws Exception
     */
    private UserInfo getCreator(String userId) throws Exception {
        UserInfo user = userDao.get(userId);
        if (null == user){
            throw new ValidateException("创建者不存在");
        }
        userDao.findLink(user, UserInfo.FIELD_COMPANY);
        if (null == user.getCompany()){
            throw new ValidateException("所属企业不存在");
        }
        return user;
    }

    private void checkUserInsertInput(String displayName, String name, String loginName, String loginPwd,
                                    String email) throws Exception {
        if (ValidatorUtils.isEmpty(displayName)){
            throw new ValidateException("显示名不能为空");
        }
        if(displayName.getBytes().length < 4 || displayName.getBytes().length > 20){
            throw new ValidateException("显示名应由4-20个字符组成");
        }
        if (ValidatorUtils.isEmpty(name)){
            throw new ValidateException("用户名不能为空");
        }
        if(name.getBytes().length < 4 || name.getBytes().length > 20){
            throw new ValidateException("用户名应由4-20个字符组成");
        }
        if (ValidatorUtils.isEmpty(loginName)){
            throw new  ValidateException("登录名不能为空");
        }
        if(!ValidatorUtils.isGeneral(loginName, 3, 12)){
            throw new  ValidateException("登录名应由3-12个英文字母 、数字和下划线组成");
        }
        if (ValidatorUtils.isEmpty(loginPwd)){
            throw new  ValidateException("密码不能为空");
        }
        if(!ValidatorUtils.isGeneral(loginPwd, 6, 16)){
            throw new  ValidateException("密码应由6-16个英文字母 、数字和下划线组成");
        }
        if (ValidatorUtils.isEmpty(email)){
            throw new  ValidateException("邮箱不能为空");
        }
        if (!ValidatorUtils.isNewEmail(email)){
            throw new  ValidateException("邮箱格式不正确");
        }
        if(email.getBytes().length < 4 || email.getBytes().length > 100){
            throw new ValidateException("邮箱应由4-100个字符组成");
        }
        List<AccountInfo> accounts = accountDao.search(Cnd.where(AccountInfo.FIELD_LOGINNAME, "=", loginName.toLowerCase()));
        if (accounts.size() > 0){
            throw new ValidateException("登录名已存在");
        }
    }

    private void checkUserUpdateInput(String userId, String displayName, String name, String loginPwd,
                                      String email) throws Exception {
        if (ValidatorUtils.isEmpty(userId)){
            throw new ValidateException("用户不存在");
        }
        if (ValidatorUtils.isEmpty(displayName)){
            throw new ValidateException("显示名不能为空");
        }
        if(displayName.getBytes().length < 4 || displayName.getBytes().length > 20){
            throw new ValidateException("显示名应由4-20个字符组成");
        }
        if (ValidatorUtils.isEmpty(name)){
            throw new ValidateException("用户名不能为空");
        }
        if(name.getBytes().length < 4 || name.getBytes().length > 20){
            throw new ValidateException("用户名应由4-20个字符组成");
        }
        if(!ValidatorUtils.isEmpty(loginPwd) && !ValidatorUtils.isGeneral(loginPwd, 6, 16)){
            throw new  ValidateException("密码应由6-16个英文字母 、数字和下划线组成");
        }
        if (ValidatorUtils.isEmpty(email)){
            throw new  ValidateException("邮箱不能为空");
        }
        if (!ValidatorUtils.isNewEmail(email)){
            throw new  ValidateException("邮箱格式不正确");
        }
        if(email.getBytes().length < 4 || email.getBytes().length > 100){
            throw new ValidateException("邮箱应由4-100个字符组成");
        }
    }
}
